<template>
  <!--components/mc-numkeyboard/mc-numkeyboard.wxml-->
  <view>
    <view class="keyboard-input-control" id="inputbox" @tap.stop="handleFocus">
      <text class="keyboard-input-unit" v-if="inputVal">￥</text>
      <view :class="'keyboard-input ' + (inputVal === '' ? 'place-holder' : '')">{{ inputVal !== '' ? inputVal :
        placeholder }}<text class="keyboard-input-cursor" v-if="showCursor"></text></view>
    </view>
    <view id="keyboardbox" @tap.stop="stopPageScroll" catchtouchmove="stopPageScroll"
      :class="'keyboard ' + (showKeyBoard ? 'keyboard--in' : '')">
      <view class="keyboard__inner">
        <view class="keyboard-body">
          <view class="keyboard-body__key">
            <view class="keyboard__inner">
              <view v-for="(item, index) in keyData" :key="index"
                class="keyboard__btn keyboard__btn_hover keyboard__btn--color-black keyboard__btn--bg-white">
                <view v-if="item === 'del'" class="keyboard__btn-inner" @tap.stop="handleDel">
                  <text class="uiconfont uicon-del"></text>
                </view>
                <view v-else class="keyboard__btn-inner" :data-value="item" @tap.stop="handleInput">{{ item }}</view>
              </view>
            </view>
          </view>
          <view class="keyboard-body__tool">
            <view
              class="keyboard__btn keyboard__btn_hover keyboard__btn_confirm keyboard__btn--color-white keyboard__btn--bg-theme"
              @tap="handleConfirm">
              <view class="keyboard__btn-inner">{{ confirmName }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      showKeyBoard: false,
      confirmName: '确定',
      keyData: [1, 2, 3, 4, 5, 6, 7, 8, 9, '.', 0, 'del'],
      inputVal: '',
      showCursor: false,
    }
  },

  components: {},
  props: {
    name: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    value: {
      type: [Number, String],
      default: '',
    },
    scrolltop: {
      type: [Number, String],
      default: 0,
    },
    scrollheight: {
      type: [Number, String],
      default: 0,
    },
    maxnum: {
      type: [Number, String],
      default: 9999999.99,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    value: {
      handler: function (newVal, oldVal) {
        const { placeholder } = this

        if (newVal != oldVal) {
          this.inputVal = newVal ? `${newVal}` : placeholder === '' ? '0' : ''
        }
      },
      immediate: true,
    },
  },
  options: {
    addGlobalClass: true,
  },
  mounted() {
    console.log("windowHeight" + this.windowHeight)
    console.log("screenHeight" + uni.getSystemInfoSync().screenHeight)
  },
  methods: {
    setVal(val) {
      // 强制刷新值
      this.inputVal = `${val}`
    },
    show() {
      const { value } = this
      this.showKeyBoard = true
      this.inputVal = `${value || 0}`
    },

    closeKeyBoard() {
      const { showKeyBoard } = this
      if (!showKeyBoard) return
      this.showKeyBoard = false
      this.showCursor = false
    },

    handleFocus() {
      const { readonly, name, showKeyBoard } = this
      if (readonly || showKeyBoard) return
      this.showCursor = true
      this.$emit('focus', {
        detail: {
          name,
        },
      })
      // setTimeout(() => {
      this.calcKeyboardPosition(true)
      // }, 500)
      // setTimeout(() => {
      this.show()
      // }, 3000)
    },

    handleInput(e) {
      const { inputVal, disabled, name, maxnum } = this
      let v = e.currentTarget.dataset.value
      let result = ''
      if (disabled) return
      if ((inputVal.indexOf('.') !== -1 && inputVal.split('.')[1].length == 2) || (inputVal.indexOf('.') !== -1 && v === '.') || Number(inputVal.concat(v)) > maxnum) return
      if (inputVal === '' && v === '.') v = '0.'

      if (inputVal === '0' && v !== '.') {
        result = v + ''
      } else {
        result = inputVal.concat(v)
      }

      this.inputVal = result
      this.$emit('input', {
        detail: {
          name,
          value: result,
        },
      })
    },

    handleDel() {
      const { inputVal, disabled, name } = this
      const index = inputVal.indexOf('.')
      let v = ''
      if (disabled || inputVal === '0') return

      if (index != -1) {
        v = inputVal.slice(0, index)
      } else {
        v = inputVal.slice(0, inputVal.length - 1)
      }

      if (v === '') v = '0'
      this.inputVal = v
      this.$emit('input', {
        detail: {
          name,
          value: v,
        },
      })
    },

    handleConfirm() {
      this.handleBlur()
      this.calcKeyboardPosition(false)
    },

    handleBlur() {
      const { name, inputVal, placeholder, showKeyBoard } = this
      const v = Number(inputVal)
      if (!showKeyBoard) return

      if (v === 0) {
        this.inputVal = placeholder === '' ? `${v}` : ''
      } else {
        this.inputVal = `${v}`
      }

      this.closeKeyBoard()
      this.$emit('confirm', {
        detail: {
          name,
          value: v,
        },
      })
    },
    querySelector(domName) {
      return new Promise((resolve) => {
        this.$nextTick(() => {
          const ele = uni.createSelectorQuery().in(this).select(domName)
          ele
            .boundingClientRect((res) => {
              resolve(res)
            })
            .exec()
        })
      })
    },
    async calcKeyboardPosition(isShow) {
      if (isShow) {
        const { scrolltop } = this
        const scrollheight = this.windowScrollHeight
        const res1 = await this.querySelector('#keyboardbox')
        const res2 = await this.querySelector('#inputbox')
        const distance = scrollheight - res2.top - res2.height
        let bottom = 0
        if (distance <= res1.height) {
          bottom = res1.height - distance + res2.height
        }
        this.$emit('keyboardshow', {
          detail: {
            keyboardStyle: `padding-bottom: ${bottom}px;`,
            scrollTop: scrolltop + bottom,
          },
        })
      } else {
        this.$emit('keyboardhide', {
          detail: {
            keyboardStyle: '',
          },
        })
      }
    },

    stopPageScroll() {
      return
    },
  },
}
</script>
<style lang="scss" scope>
@import '@/static/css/_variables.scss';

@keyframes twinkling {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.keyboard-input-control {
  position: relative;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
}

.keyboard-input-cursor {
  position: absolute;
  height: 100%;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 2px;
  background: $btn-bg;
  animation: twinkling 1s infinite;
}

.keyboard-input {
  display: inline;
  position: relative;
  line-height: 1;
  font-weight: bold;

  &.place-holder {
    font-weight: normal;
  }
}

.keyboard-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

.keyboard {
  position: fixed;
  left: 0;
  width: 100%;
  bottom: 0;
  font-size: 0;
  z-index: 10000;
  transition: all 0.3s;
  transform: translate3d(0, 100%, 0);

  &.keyboard--in {
    transform: translate3d(0, 0, 0);
  }
}

.keyboard__btn {
  position: relative;
  display: inline-block;
  vertical-align: top;
  width: 167.5rpx;
  height: 96rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
  border-radius: 8rpx;

  .keyboard__btn-inner {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    font-size: $h2-font-size;
    font-weight: bold;

    .icon-clear-digital {
      font-size: 36rpx;
    }
  }

  &_hover {
    color: #000;
  }

  &_confirm {
    display: block;
    height: 432rpx;
    margin-right: 0;
    margin-bottom: 0;
    font-weight: normal;
  }

  &--color-white {
    color: #fff;
  }

  &--color-black {
    color: #000;
  }

  &--bg-white {
    background: #fff;

    &:active {
      color: lighten(#000, 60%);
      background: darken(#fff, 15%);
    }
  }

  &--bg-theme {
    background: linear-gradient(135deg, $gradient-color1 0%, $gradient-color2 100%);

    &:active {
      background: linear-gradient(135deg, darken($gradient-color1, 15%) 0%, darken($gradient-color2, 15%) 100%);
    }
  }

  // &--bg-disabled {
  //   opacity: 0.6;
  // }
}

.keyboard-body {
  padding: 16rpx 16rpx 0;
  background: #eee;
  padding-bottom: var(--safe-bottom);

  &__key {
    display: inline-block;
    width: 550.5rpx;
    vertical-align: top;
  }

  &__tool {
    display: inline-block;
    vertical-align: top;
  }
}
</style>
